<script setup lang="ts">
import { ElMessage, ElMessageBox, TabPaneName } from 'element-plus';
import { ref, watch, } from 'vue';
import SqlEditorDialog from './SqlEditorDialog.vue'
import { useRoute, useRouter } from 'vue-router';
import { Action, Field, Model, Table } from './moduleDetailType';
import { defaultReadonlyFields, fieldType } from "@/utils/commonData"
import MessageBox from '@/components/MessageBox.vue'
import { formRequiredIsFilled } from '@/utils';
import useTableMethods from './hooks/useTableMethods';
import useFieldMethods from './hooks/useFieldMethods';
import useActionMethods from './hooks/useActionMethods';
import draggable from "vuedraggable";
import ScriptEditorDialog from '@/components/ScriptEditorDialog.vue';
import { actionType } from "@/utils/commonData"
import { Item } from 'amis-core/lib/store/list';
import { useModuleStore } from '@/store/moduleStore';
import { getCreateTableSql, moduleDetail, ModuleInterface, updateModule } from '@/api/moduleManage';
import _ from 'lodash';
const moduleStore = useModuleStore()
const route = useRoute()
const router = useRouter()

//-----------Table表单相关-------------
const { tableFormRules, formDataTable, } = useTableMethods()
//-----------Table表单相关结束-------------

//-----------Field表单相关-------------
const {
  fieldList,
  fieldItemActive,
  formDataField,
  selectFieldItem,
  orderField,
  reWriteMessageVisible,
  inputFieldName,
  deleteField,
  addField,
  fieldFormRef,
  fieldFormRules,
  fieldInputNameRef,
  reWriteMessage,
} = useFieldMethods()
//-----------Field表单相关结束-------------

//-----------Action表单相关-------------
const {
  actionList,
  addAction,
  deleteAction,
  selectActionItem,
  resetActionForm,
  actionItemActive,
  actionFormRef,
  formDataAction,
  actionFormRules,
  actionActiveIndex,
} = useActionMethods()
//-----------Action表单相关结束-------------

//-----------tab栏相关-------------
const tableFormRef = ref()
const currentTab = ref('1')


/**
 * 验证表单和参数列表字段完整性
 * @params validateAction: 是否执行方法验证，默认为 true，要验证方法表单的完整性（方法列表可以为空）
 * @returns 验证结果，返回true表示验证通过，返回false表示验证失败
 */
function validateFormAndShowTip(validateAction: boolean = true) {
  // 验证table表单是否已经填写
  tableFormRef.value && tableFormRef.value.validate()
  if (!formDataTable.value.name) {
    ElMessage.error('请填写表名')
    return false
  }

  // 验证是否添加了字段
  if (fieldList.value.length == 0) {
    ElMessage.error('至少新增一个字段')
    return false
  }
  // fieldList长度为0，则直接返回false
  if (fieldList.value.length == 0) {
    ElMessage.error('至少新增一个字段')
    return false
  }

  fieldFormRef.value && fieldFormRef.value.validate()
  // fieldList长度不为0，验证是否必填项都填写了
  for (let i = 0; i < fieldList.value.length; i++) {
    let isFullField = formRequiredIsFilled(fieldFormRules, fieldList.value[i])
    if (!isFullField) {
      ElMessage.error('有字段必填项未填写')
      return false
    }
  }
  if (validateAction) {
    actionFormRef.value && actionFormRef.value.validate()
    // 没添加action，直接通过
    if (actionList.value.length == 0) {
      return true
    } else {
      // 验证必填字段表单是否已经填写
      for (let i = 0; i < actionList.value.length; i++) {
        let isFullAction = formRequiredIsFilled(actionFormRules, actionList.value[i])
        if (!isFullAction) {
          ElMessage.error('有方法必填项未填写')
          return false
        }
      }
    }
  }

  return true
}
//-----------tab栏相关结束-------------


//-----------整个表单提交-------------
const formData = ref<Model>({
  table: {
    name: "",
    aliasName: "",
    comment: "",
    charset: "utf8mb4",
    rowFormat: "DYNAMIC",
    collate: "utf8mb4_0900_ai_ci",
    engine: "InnoDB"
  } as Table,
  field: [] as Field[],
  action: [] as Action[]
});

function submit() {
  let isValidateOk = validateFormAndShowTip()

  moduleDetailFormData.value!.data.table = formDataTable.value
  moduleDetailFormData.value!.data.field = fieldList.value
  moduleDetailFormData.value!.data.action = actionList.value

  if (isValidateOk) {
    // TODO: 提交表单
    updateModule(moduleDetailFormData.value).then(res => {
      ElMessage.success('提交成功')
      moduleDetailFormDataT = _.cloneDeep(moduleDetailFormData.value) as any
    })
  } else {
  }
}
//-----------整个表单提交结束-------------

function pageBack() {
  if (JSON.stringify(moduleDetailFormDataT) == JSON.stringify(moduleDetailFormData.value)) {
    router.go(-1)
  } else {
    ElMessageBox.confirm('返回后未提交的数据将丢失，确定要返回上一页吗？', '提示', { type: 'warning' }).then(() => {
      router.go(-1)
    }).catch(() => { })
  }
}

function onDragEnd(a: any, b: any, c: any) {
  fieldList.value = fieldList.value.map((item: any, index: number) => {
    return {
      ...item,
      sort: index
    }
  })
}

const scriptDiaVisible = ref(false)
const scriptDiaIndex = ref(0)// 0:前置脚本  1:后置脚本
const currentActionScript = ref('')

function openScriptDia(index: number) {
  scriptDiaIndex.value = index
  scriptDiaVisible.value = true
  switch (index) {
    case 0:
      currentActionScript.value = formDataAction.value.before
      break
    case 1:
      currentActionScript.value = formDataAction.value.after
      break
    case 2:
      currentActionScript.value = formDataAction.value.shell
  }
}

function scriptDiaClose() {
  scriptDiaVisible.value = false
}

/**
 * 脚本编辑器保存返回数据
 *
 * @param val - 变更的值
 */
function actionDetailChange(val: any) {
  formData.value.action[actionActiveIndex.value].detail = JSON.parse(JSON.stringify(val))
  actionFormRef.value && actionFormRef.value.validate()// 重新验证表单数据
}

/**
 * 前置后置脚本修改后保存并关闭弹窗
 *
 * @param value 脚本内容变化后的新值
 */
function scriptChange(value: string) {

  scriptDiaVisible.value = false
  if (scriptDiaIndex.value == 0) {
    formData.value.action[actionActiveIndex.value].before = value
  }
  if (scriptDiaIndex.value == 1) {
    formData.value.action[actionActiveIndex.value].after = value
  }
  if (scriptDiaIndex.value == 2) {
    formData.value.action[actionActiveIndex.value].shell = value
  }
}

const moduleDetailFormData = ref<ModuleInterface>()
let moduleDetailFormDataT = {}// 深拷贝一份原始数据，用于判断是否有改动

function getModuleDetail() {
  let id: string = route.query.id as string
  moduleDetail(id).then(res => {
    moduleDetailFormData.value = res.data
    formDataTable.value = moduleDetailFormData.value!.data.table
    fieldList.value = moduleDetailFormData.value!.data.field
    actionList.value = moduleDetailFormData.value!.data.action
    moduleDetailFormDataT = _.cloneDeep(moduleDetailFormData.value) as any
  })
}
/**
 * 判断给定字段是否为只读字段
 *
 * @param field 字段对象，包含字段名称和值等信息
 * @returns 如果字段在默认只读字段列表中，则返回true，否则返回false
 */
const fieldReadonly = (field: Field) => {
  return defaultReadonlyFields.includes(field.name)
}


const createTableScript = ref('CREATE TABLE `t_user`( \n`id` varchar(36) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL  COMMENT 主键id,\n`create_by` varchar(36) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL  COMMENT 创建人,\n`create_time`  CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL  COMMENT 创建时间,\n`update_by` varchar(36) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL  COMMENT 更新人,\n`update_time`  CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL  COMMENT 更新时间,\n`remarks` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL  COMMENT 备注,\n`del_flag` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL  COMMENT 删除标识（0：未删除 1：已删除）,\n`username` varchar(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL ,\n`password` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL ,\nPRIMARY KEY (`id`)  USING BTREE \n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;')
const showBuildCreateTableScriptDialog = ref(false)
/**
 * 根据已有的字段列表fieldList，构建表结构
 *
 */
function buildCreateTableScript() {
  let id: string = route.query.id as string

  let isFullTableAndField = validateFormAndShowTip(false)
  if (!isFullTableAndField) return;

  moduleDetailFormData.value!.data.table = formDataTable.value
  moduleDetailFormData.value!.data.field = fieldList.value
  moduleDetailFormData.value!.data.action = actionList.value

  if (isFullTableAndField) {
    // TODO: 提交表单
    updateModule(moduleDetailFormData.value).then(res => {
      getCreateTableSql({ id }).then(res => {
        createTableScript.value = res.data
        showBuildCreateTableScriptDialog.value = true
      })
      moduleDetailFormDataT = _.cloneDeep(moduleDetailFormData.value) as any
    })
  }

}

/**
 * 复制SQL语句到剪贴板
 */
function copySql() {
  navigator.clipboard.writeText(createTableScript.value)
  ElMessage({
    type: 'success',
    message: '复制成功！'
  })
  showBuildCreateTableScriptDialog.value = false

}

function fieldTypeChange() {
  if (formDataField.value.type == 'decimal') {
    formDataField.value.maxLength = 10
  } else {
    formDataField.value.maxLength = 255
  }
}

watch(() => route, (val: any) => {
  getModuleDetail()
}, {
  deep: true,
  immediate: true
})

watch(() =>
  [
    formDataTable.value,
    fieldList.value,
    actionList.value,
  ],
  () => {
    formData.value.table = formDataTable.value
    formData.value.field = fieldList.value
    formData.value.action = actionList.value
    moduleStore.setCurrentModule(formData.value)
  },
  {
    deep: true,
    immediate: true
  }
)
</script>

<template>
  <div class="pageTitle">{{ route.meta.title }}</div>
  <div class="moduleDetailPageMain">
    <div class="tabbox_header">
      <el-button type="primary" icon="" link @click="buildCreateTableScript">生成表结构</el-button>
      <el-button type="" @click="pageBack">返回</el-button>
      <el-button type="primary" @click="submit">提交</el-button>
    </div>
    <el-tabs type="border-card" v-model="currentTab">
      <template>
        <el-icon><Select /></el-icon>
      </template>
      <!-- table -->
      <el-tab-pane label="表" name="1">
        <el-form :model="formDataTable" ref="tableFormRef" label-width="120px" :rules="tableFormRules" @submit.prevent>
          <el-form-item label="表名" prop="name">
            <el-input v-model="formDataTable.name" placeholder="请输入表名"></el-input>
          </el-form-item>
          <el-form-item label="表别名" prop="aliasName">
            <el-input v-model="formDataTable.aliasName" placeholder="请输入表别名"></el-input>
          </el-form-item>
          <el-form-item label="注释">
            <el-input v-model="formDataTable.comment" maxlength="32" placeholder="请输入注释"></el-input>
          </el-form-item>
          <!-- <el-form-item label="字符集">
            <el-select v-model="formDataTable.charset" placeholder="请选择字符集">
              <el-option label="utf8mb4" value="utf8mb4"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="行格式">
            <el-select v-model="formDataTable.rowFormat" placeholder="请选择行格式">
              <el-option label="DYNAMIC" value="DYNAMIC"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="排序规则">
            <el-select v-model="formDataTable.collate" placeholder="请选择排序规则">
              <el-option label="utf8_general_ci" value="utf8_general_ci"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="存储引擎">
            <el-select v-model="formDataTable.engine" placeholder="请选择存储引擎">
              <el-option label="InnoDB" value="InnoDB"></el-option>
            </el-select>
          </el-form-item> -->
        </el-form>
      </el-tab-pane>
      <!-- fields -->
      <el-tab-pane label="字段" name="2">
        <div class="field_box">
          <div class="field_box_left">
            <el-button type="primary" @click="addField" link icon="Plus" style="margin-bottom:10px">新增字段</el-button>
            <draggable :list="fieldList" ghost-class="ghost" chosen-class="chosenClass" animation="300"
              @end="onDragEnd">
              <template #item="{ element }">
                <div @click="selectFieldItem(fieldItemActive, element)"
                  :class="{ 'field_item': true, 'field_item_active': fieldItemActive == element.id }"
                  :key="element.name">
                  <span>{{ element.name }}</span>
                  <div class="field_item_btns">
                    <el-button type="danger" style="margin-left:5px;" @click.stop="deleteField(element)" link
                      icon="Delete" v-if="!fieldReadonly(element)"></el-button>
                  </div>
                </div>
              </template>
            </draggable>
          </div>
          <div class="field_box_right">
            <div class="field_box_right_title" v-if="fieldItemActive > -1">编辑字段</div>
            <el-form :model="formDataField" ref="fieldFormRef" :rules="fieldFormRules" v-if="fieldItemActive > -1"
              label-width="170px" @submit.prevent>
              <el-form-item label="字段名称" prop="name">
                <el-input v-model="formDataField.name" ref="fieldInputNameRef" :readonly="fieldReadonly(formDataField)"
                  @blur="inputFieldName" placeholder="请输入字段名称"></el-input>
              </el-form-item>
              <el-form-item label="字段别名" prop="aliasName">
                <el-input v-model="formDataField.aliasName" placeholder="请输入字段名称"
                  :readonly="fieldReadonly(formDataField)"></el-input>
              </el-form-item>
              <el-form-item label="字段类型" prop="type">
                <el-select :disabled="fieldReadonly(formDataField)" filterable v-model="formDataField.type"
                  @change="fieldTypeChange" placeholder="请选择字段类型">
                  <el-option v-for="item in fieldType" :label="item" :value="item"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="是否必填">
                <el-switch :disabled="fieldReadonly(formDataField)" inactive-text="否" active-text="是"
                  v-model="formDataField.required" placeholder="请输入备注"></el-switch>
              </el-form-item>
              <el-form-item label="是否为主键" prop="primaryKey" v-if="formDataField.required">
                <el-switch :disabled="fieldReadonly(formDataField)" inactive-text="否" active-text="是"
                  v-model="formDataField.primaryKey" placeholder="请输入字段名称"></el-switch>
              </el-form-item>

              <el-form-item label="根据当前时间戳更新" prop="updateByCurrentTime" v-if="formDataField.type == 'datetime'">
                <el-switch v-model="formDataField.updateByCurrentTime" :disabled="fieldReadonly(formDataField)"
                  inactive-text="否" active-text="是" />
              </el-form-item>
              <el-form-item label="注释" prop="comment">
                <el-input :readonly="fieldReadonly(formDataField)" v-model="formDataField.comment" maxlength="32"
                  placeholder="请输入注释"></el-input>
              </el-form-item>
              <el-form-item label="默认值" prop="defaultValue">
                <el-input v-model="formDataField.defaultValue" :disabled="fieldReadonly(formDataField)"
                  placeholder="请输入默认值"></el-input>
                <!-- <el-select v-model="formDataField.defaultValue" :disabled="fieldReadonly(formDataField)" placeholder="请选择默认值"
                  clearable>
                  <el-option label="CURRENT_TIMESTAMP" value="CURRENT_TIMESTAMP"></el-option>
                </el-select> -->
              </el-form-item>
              <el-form-item label="长度" prop="maxLength">
                <el-input-number :disabled="fieldReadonly(formDataField)" class="maxLengthInput" :min="1"
                  v-model="formDataField.maxLength" controls-position="right" placeholder="请输入字段长度"></el-input-number>
              </el-form-item>
              <el-form-item label="小数位数" prop="decimalDigits" v-if="formDataField.type == 'decimal'">
                <el-input-number class="numberInput" controls-position="right" disabled
                  v-model="formDataField.decimalDigits" :min="0" />
              </el-form-item>
              <!-- <el-form-item label="字符集">
                <el-select :disabled="fieldReadonly(formDataField)" v-model="formDataField.charset"
                  placeholder="请选择字符集">
                  <el-option label="utf8mb4" value="utf8mb4"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="排序规则">
                <el-select :disabled="fieldReadonly(formDataField)" v-model="formDataField.collate"
                  placeholder="请选择排序规则">
                  <el-option label="utf8mb4_0900_ai_ci" value="utf8mb4_0900_ai_ci"></el-option>
                </el-select>
              </el-form-item> -->
            </el-form>
            <el-empty description="请选择或添加字段" v-else />
          </div>
        </div>
      </el-tab-pane>
      <!-- action -->
      <el-tab-pane label="方法" name="3">
        <div class="field_box">
          <div class="field_box_left">
            <el-button type="primary" @click="addAction" link icon="Plus" style="margin-bottom:10px">新增方法</el-button>
            <div @click="selectActionItem(actionItemActive, item)"
              :class="{ 'field_item': true, 'field_item_active': actionItemActive == item.id }"
              v-for="item in actionList">
              <span>{{ item.name }}</span>
              <el-button type="danger" @click.stop="deleteAction(item)" link icon="Delete"></el-button>
            </div>
          </div>
          <div class="field_box_right">
            <div class="field_box_right_title" v-if="actionItemActive > -1">编辑方法 </div>
            <div class="sqlEditor">
              <el-form :model="formDataAction" v-if="actionItemActive > -1" ref="actionFormRef" :rules="actionFormRules"
                label-width="100px" @submit.prevent>
                <el-form-item label="方法名称" prop="name">
                  <el-input v-model="formDataAction.name" placeholder="请输入方法名称"></el-input>
                </el-form-item>
                <el-form-item label="方法类型" prop="type">
                  <el-select filterable v-model="formDataAction.type" placeholder="请选择方法类型">
                    <el-option :label="item.label" v-for="item in actionType" :value="item.value" />
                  </el-select>
                </el-form-item>
                <el-form-item label="详情" prop="detail.saveScript" v-if="formDataAction.type != 'CustomScript'">
                  <sql-editor-dialog :detail="formDataAction.detail" :type="formDataAction.type"
                    @onChange="actionDetailChange" :table-name="formDataTable.name" />
                  <input type="hidden" v-model="formDataAction.detail.saveScript" />
                </el-form-item>
                <el-form-item label="脚本" prop="shell" v-if="formDataAction.type == 'CustomScript'">
                  <el-button link type="primary" icon="Edit" @click="openScriptDia(2)">编辑脚本</el-button>
                  <input type="hidden" v-model="formDataAction.shell" />
                </el-form-item>
                <el-form-item label="备注" prop="label">
                  <el-input v-model="formDataAction.label" placeholder="请输入备注"></el-input>
                </el-form-item>
                <el-form-item label="前置脚本" v-if="formDataAction.type != 'CustomScript'">
                  <el-button link type="primary" icon="Edit" @click="openScriptDia(0)">编辑前置脚本</el-button>
                </el-form-item>
                <el-form-item label="后置脚本" v-if="formDataAction.type != 'CustomScript'">
                  <el-button link type="primary" icon="Edit" @click="openScriptDia(1)">编辑后置脚本</el-button>
                </el-form-item>
              </el-form>
              <el-empty description="请选择或添加方法" v-else />
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    <!-- 编辑前置脚本后置脚本的弹窗 -->
    <script-editor-dialog :show="scriptDiaVisible" :value="currentActionScript" :index="scriptDiaIndex"
      @onChange="scriptChange" @close="scriptDiaClose" />
  </div>

  <!-- 重新填写弹窗 -->
  <message-box :center="false" title="字段名重复" content-text="字段名重复，请重新填写" v-model:visible="reWriteMessageVisible">
    <template #buttonGroup>
      <el-button type="primary" @click="reWriteMessage">重新编辑</el-button>
    </template>
  </message-box>
  <!-- 建表的脚本弹窗 -->
  <el-dialog title='创建表SQL' v-model='showBuildCreateTableScriptDialog' @close='showBuildCreateTableScriptDialog = false'
    width='1200px'>
    <div class="sqlCreateTable">
      <pre class="sqlCreateTable_preview">{{ createTableScript }}</pre>
      <div class="sqlCreateTable_footer" style="display: flex; justify-content: end;">
        <el-button type='success' icon="CopyDocument" @click='copySql'>复制</el-button>
        <el-button type='primary' @click='showBuildCreateTableScriptDialog = false'>关闭</el-button>
      </div>
    </div>
  </el-dialog>

</template>

<style scoped lang="scss">
.numberInput {
  width: 100%;

  &:deep(input) {
    text-align: left;

  }
}

.sqlCreateTable {

  &_preview {
    overflow: auto;
    background: black;
    margin: 0;
    overflow: auto;
    padding: 10px;
    color: white;

    &::-webkit-scrollbar {
      width: 12px;
      /* 垂直滚动条宽度 */
      height: 12px;
      /* 水平滚动条高度 */
    }

    &::-webkit-scrollbar-track {
      background: #3e3e3e;
      border-radius: 1px;
    }

    &::-webkit-scrollbar-thumb {
      background: #888;
      border-radius: 1px;
    }

    &::-webkit-scrollbar-thumb:hover {
      background: #777777;
    }
  }

  &_footer {
    margin-top: 10px;
  }
}

:deep(.el-tabs--border-card>.el-tabs__header .el-tabs__item) {
  color: #474747;
}

:deep(.el-tabs__item.is-disabled) {
  color: #d7d7d7 !important;
}

:deep(.el-tabs__item.is-active) {
  color: #2890f7 !important;
}

.ghost {
  border: solid 1px rgb(19, 41, 239) !important;
}

.chosenClass {
  opacity: 1;
  border: solid 1px red;
}

.fallbackClass {
  background-color: aquamarine;
}

.maxLengthInput {
  width: 100% !important;

  :deep(.el-input__inner) {
    text-align: left;
  }
}

.sqlEditor {
  &_title {
    display: flex;
    justify-content: start;
    align-items: center;
    margin-bottom: 10px;
  }
}

.moduleDetailPageMain {
  height: 100vh;
  box-sizing: border-box;
  padding: 15px;
  position: relative;
}

.field {
  &_item {
    display: flex;
    justify-content: space-between;
    width: 98%;
    font-size: 15px;
    margin: 5px auto;
    border: 1px solid #eaeaea;
    padding: 5px;
    cursor: pointer;
    border-radius: 5px;
    color: #4e4e4e;

    &_active {
      background-color: #d8f2ff !important;
    }

    &:hover {
      background-color: #f6fcff;
    }

    &_btns {
      width: 90px;
      display: flex;
      justify-content: end;
    }
  }

  &_box {
    display: flex;
    justify-content: space-between;

    &_left {
      width: 25%;
      padding: 15px;
      border: 1px solid #eaeaea;
      max-height: 90vh;
      overflow: auto;
    }

    &_right {
      width: 74%;
      padding: 15px;
      border: 1px solid #eaeaea;
      max-height: 90vh;
      overflow: auto;

      &_title {
        font-size: 15px;
        margin-bottom: 15px;
      }
    }
  }
}

.tabbox {
  &_header {
    display: flex;
    justify-content: end;
    margin-bottom: 15px;
    position: absolute;
    right: 30px;
    top: 18px;
    z-index: 1;
  }

  &_footer {
    display: flex;
    justify-content: end;
    margin-top: 15px;
  }
}
</style>